package com.ll.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ll.common.utils.R;
import com.ll.gulimall.cart.feign.ProductFeignService;
import com.ll.gulimall.cart.interceptor.CartInterceptor;
import com.ll.gulimall.cart.service.CartService;
import com.ll.gulimall.cart.to.UserInfoTo;
import com.ll.gulimall.cart.vo.Cart;
import com.ll.gulimall.cart.vo.CartItem;
import com.ll.gulimall.cart.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    ProductFeignService productFeignService;

    private final String cartKeyPrefix = "GULIMALL:CART:";

    /**
     * 添加购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addToCart(String skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cart = getCartRedis();

        //拿到购物车数据
        String ops = (String) cart.get(skuId);
        if (StringUtils.isEmpty(ops)) {
            //没有这个购物车 新增
            //1.购物车数据
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    //响应成功   //1.远程查询商品信息
                    SkuInfoVo skuInfo = info.getData(new TypeReference<SkuInfoVo>() {
                    }, "skuInfo");
                    cartItem.setCheck(true);
                    cartItem.setCount(num);
                    cartItem.setImgage(skuInfo.getSkuDefaultImg());
                    cartItem.setPrice(skuInfo.getPrice());
                    cartItem.setSkuId(skuInfo.getSkuId());
                    cartItem.setTitle(skuInfo.getSkuTitle());
                }
            }, executor);

            CompletableFuture<Void> saleAttrFuture = CompletableFuture.runAsync(() -> {
                //2.远程查询商品属性信息
                List<String> saleAttr = productFeignService.getSkuSaleAttrBySkuId(Integer.parseInt(skuId));
                cartItem.setSkuAttr(saleAttr);
            }, executor);

            CompletableFuture.allOf(skuInfoFuture, saleAttrFuture).get();
            //3、放入购物车
            String jsonCart = JSON.toJSONString(cartItem);
            cart.put(skuId, jsonCart);
            return cartItem;

        } else {
            //修改购物车状态
            CartItem cartItem = JSON.parseObject(ops, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);

            //更新Reids
            cart.put(skuId, JSON.toJSONString(cartItem));
            return cartItem;
        }


    }

    /**
     * 根据SkuId查询购物车数据
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(String skuId) {

        BoundHashOperations<String, Object, Object> cart = getCartRedis();
        String jsonCart = (String) cart.get(skuId);

        return JSON.parseObject(jsonCart, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        //1.根据用户登录状态获取不同的购物车数据
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        if (!StringUtils.isEmpty(userInfoTo.getUserId())) {
            //已登录
            cartKey = cartKeyPrefix + userInfoTo.getUserId();
            //如果已经登录 则需要把临时购物车数据合并到购物车
            //获取临时购物车数据
            List<CartItem> cartItems = getCartItems(cartKeyPrefix + userInfoTo.getUser_key());
            if (cartItems != null) {
                //有数据 进行合并
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId().toString(), cartItem.getCount());
                }
            }
            //合并完成返回新数据
            List<CartItem> items = getCartItems(cartKeyPrefix + userInfoTo.getUserId());
            cart.setItems(items);
            //删除临时购物车数据
            clearCart(cartKeyPrefix + userInfoTo.getUser_key());
            return cart;

        } else {
            //未登录
            cartKey = cartKeyPrefix + userInfoTo.getUser_key();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        }

    }

    @Override
    public void clearCart(String cartKey) {

        redisTemplate.delete(cartKey);

    }

    /**
     * 修改购物项选中
     *
     * @param skuId
     * @param checked
     */
    @Override
    public void checkedItem(Long skuId, Integer checked) {

        CartItem cartItem = getCartItem(skuId.toString());
        cartItem.setCheck(checked == 1 ? true : false);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cart = getCartRedis();
        cart.put(skuId.toString(), jsonString);
    }

    /**
     * 修改购物项数量
     *
     * @param skuId
     * @param num
     */
    @Override
    public void changeNum(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId.toString());
        cartItem.setCount(num);
        String jsonString = JSON.toJSONString(cartItem);
        //修改
        getCartRedis().put(skuId.toString(), jsonString);

    }

    /**
     * 删除购物项
     *
     * @param skuId
     */
    @Override
    public void delCartItem(Long skuId) {

        getCartRedis().delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            String cartKey = cartKeyPrefix + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> {
                return item.getCheck();
            }).map(item -> {
                //TODO 获取商品最新数据
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());

            return collect;

        } else {
            return null;
        }


    }

    /**
     * 获取指定key购物车数据
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        if (values != null) {
            //遍历value得到每个购物项
            List<CartItem> collect = values.stream().map((obj) -> {
                String json = obj.toString();
                CartItem cartItem = JSON.parseObject(json, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取cart的hash对对象
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartRedis() {
        //1.获取用户是否登录 获取相应的redis_key
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //用户登录的Key
            cartKey = cartKeyPrefix + userInfoTo.getUserId();
        } else {
            //用户未登录的Key
            cartKey = cartKeyPrefix + userInfoTo.getUser_key();
        }
        //绑定Redis方便操作
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        return ops;
    }
}
